// DOM 操作示例和交互功能

// 等待DOM加载完成
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOM已加载完成');
    
    // 初始化所有功能
    initMobileMenu();
    initSmoothScroll();
    initContactForm();
    initScrollEffects();
    initTypingEffect();
    initBackToTop();
    initLanguageSwitch();
    initThemeSwitch();
});

// 移动端菜单切换功能
function initMobileMenu() {
    const hamburger = document.querySelector('.hamburger');
    const navMenu = document.querySelector('.nav-menu');
    const navLinks = document.querySelectorAll('.nav-link');

    // 汉堡菜单点击事件
    hamburger.addEventListener('click', function() {
        hamburger.classList.toggle('active');
        navMenu.classList.toggle('active');
        
        // 添加动画效果
        const bars = hamburger.querySelectorAll('.bar');
        bars.forEach((bar, index) => {
            bar.style.transition = 'all 0.3s ease';
        });
    });

    // 点击导航链接时关闭菜单
    navLinks.forEach(link => {
        link.addEventListener('click', function() {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        });
    });

    // 点击页面其他区域关闭菜单
    document.addEventListener('click', function(event) {
        const isClickInsideNav = navMenu.contains(event.target) || hamburger.contains(event.target);
        
        if (!isClickInsideNav && navMenu.classList.contains('active')) {
            hamburger.classList.remove('active');
            navMenu.classList.remove('active');
        }
    });
}

// 平滑滚动功能
function initSmoothScroll() {
    // 为所有内部链接添加平滑滚动
    const links = document.querySelectorAll('a[href^="#"]');
    
    links.forEach(link => {
        link.addEventListener('click', function(e) {
            e.preventDefault();
            
            const targetId = this.getAttribute('href').substring(1);
            const targetElement = document.getElementById(targetId);
            
            if (targetElement) {
                const headerOffset = 80; // 导航栏高度
                const elementPosition = targetElement.offsetTop;
                const offsetPosition = elementPosition - headerOffset;
                
                window.scrollTo({
                    top: offsetPosition,
                    behavior: 'smooth'
                });
            }
        });
    });
}

// 滚动到指定部分的功能
function scrollToSection(sectionId) {
    const targetElement = document.getElementById(sectionId);
    
    if (targetElement) {
        const headerOffset = 80;
        const elementPosition = targetElement.offsetTop;
        const offsetPosition = elementPosition - headerOffset;
        
        window.scrollTo({
            top: offsetPosition,
            behavior: 'smooth'
        });
    }
}

// 联系表单处理
function initContactForm() {
    const contactForm = document.getElementById('contactForm');
    
    if (contactForm) {
        contactForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            // 获取表单数据
            const formData = new FormData(this);
            const name = formData.get('name');
            const email = formData.get('email');
            const message = formData.get('message');
            
            // 简单的表单验证
            if (validateForm(name, email, message)) {
                // 模拟发送表单
                simulateFormSubmission(name, email, message);
            }
        });
    }
}

// 表单验证
function validateForm(name, email, message) {
    // 验证姓名
    if (!name || name.trim().length < 2) {
        showNotification('请输入有效的姓名（至少2个字符）', 'error');
        return false;
    }
    
    // 验证邮箱
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email || !emailRegex.test(email)) {
        showNotification('请输入有效的邮箱地址', 'error');
        return false;
    }
    
    // 验证消息
    if (!message || message.trim().length < 10) {
        showNotification('请输入消息（至少10个字符）', 'error');
        return false;
    }
    
    return true;
}

// 模拟表单提交
function simulateFormSubmission(name, email, message) {
    const submitButton = document.querySelector('.submit-button');
    const originalText = submitButton.textContent;
    
    // 显示加载状态
    submitButton.textContent = '发送中...';
    submitButton.disabled = true;
    
    // 模拟网络请求延迟
    setTimeout(() => {
        // 重置表单
        document.getElementById('contactForm').reset();
        
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
        
        // 显示成功消息
        showNotification(`感谢您的消息，${name}！我会尽快回复您。`, 'success');
        
        console.log('表单提交成功:', { name, email, message });
    }, 2000);
}

// 显示通知消息
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.textContent = message;
    
    // 添加样式
    notification.style.cssText = `
        position: fixed;
        top: 100px;
        right: 20px;
        padding: 1rem 1.5rem;
        border-radius: 5px;
        color: white;
        font-weight: 500;
        z-index: 10000;
        transform: translateX(100%);
        transition: transform 0.3s ease;
        max-width: 300px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.15);
    `;
    
    // 根据类型设置背景色
    const colors = {
        success: '#27ae60',
        error: '#e74c3c',
        info: '#3498db',
        warning: '#f39c12'
    };
    notification.style.backgroundColor = colors[type] || colors.info;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.style.transform = 'translateX(0)';
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.style.transform = 'translateX(100%)';
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 4000);
}

// 滚动效果
function initScrollEffects() {
    // 导航栏滚动效果
    let lastScrollTop = 0;
    const header = document.querySelector('.header');
    
    window.addEventListener('scroll', function() {
        const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
        
        // 添加滚动时的阴影效果
        if (scrollTop > 50) {
            header.style.boxShadow = '0 2px 20px rgba(0,0,0,0.1)';
        } else {
            header.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
        }
        
        // 添加滚动方向检测（可选功能）
        if (scrollTop > lastScrollTop && scrollTop > 200) {
            // 向下滚动
            header.style.transform = 'translateY(-100%)';
        } else {
            // 向上滚动
            header.style.transform = 'translateY(0)';
        }
        
        lastScrollTop = scrollTop;
    });
    
    // 添加导航栏过渡效果
    header.style.transition = 'all 0.3s ease';
}

// 打字机效果
function initTypingEffect() {
    const heroTitle = document.querySelector('.hero-content h1');
    if (heroTitle) {
        const text = heroTitle.textContent;
        heroTitle.textContent = '';
        let index = 0;
        
        function typeText() {
            if (index < text.length) {
                heroTitle.textContent += text.charAt(index);
                index++;
                setTimeout(typeText, 100);
            }
        }
        
        // 延迟开始打字效果
        setTimeout(typeText, 500);
    }
}

// 返回顶部按钮功能
function initBackToTop() {
    const backToTopButton = document.getElementById('backToTop');
    
    // 监听滚动事件
    window.addEventListener('scroll', function() {
        if (window.pageYOffset > 300) {
            backToTopButton.classList.add('show');
        } else {
            backToTopButton.classList.remove('show');
        }
    });
    
    // 点击返回顶部
    backToTopButton.addEventListener('click', function() {
        window.scrollTo({
            top: 0,
            behavior: 'smooth'
        });
    });
}

// 项目卡片悬停效果增强
document.addEventListener('DOMContentLoaded', function() {
    const projectCards = document.querySelectorAll('.project-card');
    
    projectCards.forEach(card => {
        card.addEventListener('mouseenter', function() {
            this.style.transform = 'translateY(-10px) scale(1.02)';
        });
        
        card.addEventListener('mouseleave', function() {
            this.style.transform = 'translateY(0) scale(1)';
        });
    });
});

// 技能列表动画
document.addEventListener('DOMContentLoaded', function() {
    const skillsItems = document.querySelectorAll('.skills-list li');
    
    const observer = new IntersectionObserver((entries) => {
        entries.forEach((entry, index) => {
            if (entry.isIntersecting) {
                setTimeout(() => {
                    entry.target.style.opacity = '1';
                    entry.target.style.transform = 'translateX(0)';
                }, index * 100);
            }
        });
    });
    
    skillsItems.forEach(item => {
        item.style.opacity = '0';
        item.style.transform = 'translateX(-20px)';
        item.style.transition = 'all 0.5s ease';
        observer.observe(item);
    });
});

// 工具函数：防抖
function debounce(func, wait) {
    let timeout;
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 工具函数：节流
function throttle(func, limit) {
    let inThrottle;
    return function() {
        const args = arguments;
        const context = this;
        if (!inThrottle) {
            func.apply(context, args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 页面加载完成后的初始化日志
window.addEventListener('load', function() {
    console.log('✅ 作品集网站加载完成！');
    console.log('📱 移动端菜单已初始化');
    console.log('🎯 平滑滚动已启用');
    console.log('📧 联系表单已准备就绪');
    console.log('🌐 多语言支持已激活');
    console.log('🌙 深色模式支持已激活');
    console.log('✨ 所有交互功能已激活');
});

// 主题切换功能
function initThemeSwitch() {
    const themeToggle = document.getElementById('theme-toggle');
    const themeIcon = document.getElementById('theme-icon');
    const htmlElement = document.documentElement;
    
    // 从localStorage获取保存的主题设置
    const savedTheme = localStorage.getItem('preferredTheme') || 'light';
    
    // 初始化主题
    setTheme(savedTheme);
    
    // 绑定主题切换按钮事件
    if (themeToggle) {
        themeToggle.addEventListener('click', function() {
            const currentTheme = htmlElement.getAttribute('data-theme') || 'light';
            const newTheme = currentTheme === 'light' ? 'dark' : 'light';
            setTheme(newTheme);
            
            // 保存主题偏好
            localStorage.setItem('preferredTheme', newTheme);
        });
    }
}

// 设置主题
function setTheme(theme) {
    const htmlElement = document.documentElement;
    const themeIcon = document.getElementById('theme-icon');
    
    // 设置data-theme属性
    htmlElement.setAttribute('data-theme', theme);
    
    // 更新图标
    if (themeIcon) {
        themeIcon.className = theme === 'dark' ? 'fas fa-moon' : 'fas fa-sun';
    }
    
    console.log(`🌙 主题已切换到: ${theme === 'dark' ? '深色模式' : '浅色模式'}`);
}

// 语言切换功能
function initLanguageSwitch() {
    const langButtons = document.querySelectorAll('.lang-btn');
    const htmlElement = document.documentElement;
    
    // 从localStorage获取保存的语言设置
    const savedLang = localStorage.getItem('preferredLanguage') || 'zh';
    
    // 初始化语言
    setLanguage(savedLang);
    
    // 绑定语言切换按钮事件
    langButtons.forEach(button => {
        button.addEventListener('click', function() {
            const lang = this.getAttribute('data-lang');
            setLanguage(lang);
            
            // 更新按钮状态
            langButtons.forEach(btn => btn.classList.remove('active'));
            this.classList.add('active');
            
            // 保存语言偏好
            localStorage.setItem('preferredLanguage', lang);
        });
    });
}

// 设置语言
function setLanguage(lang) {
    const htmlElement = document.documentElement;
    htmlElement.setAttribute('lang', lang === 'zh' ? 'zh-CN' : 'en');
    
    // 更新所有带有语言属性的元素
    const elements = document.querySelectorAll('[data-lang-zh][data-lang-en]');
    elements.forEach(element => {
        const text = element.getAttribute(`data-lang-${lang}`);
        if (text) {
            element.textContent = text;
        }
    });
    
    // 更新表单验证消息
    updateFormValidationMessages(lang);
    
    console.log(`🌐 语言已切换到: ${lang === 'zh' ? '中文' : 'English'}`);
}

// 更新表单验证消息
function updateFormValidationMessages(lang) {
    const messages = {
        zh: {
            nameError: '请输入有效的姓名（至少2个字符）',
            emailError: '请输入有效的邮箱地址',
            messageError: '请输入消息（至少10个字符）',
            sending: '发送中...',
            sendSuccess: '感谢您的消息，{name}！我会尽快回复您。'
        },
        en: {
            nameError: 'Please enter a valid name (at least 2 characters)',
            emailError: 'Please enter a valid email address',
            messageError: 'Please enter a message (at least 10 characters)',
            sending: 'Sending...',
            sendSuccess: 'Thank you for your message, {name}! I will reply to you soon.'
        }
    };
    
    // 保存当前语言的消息到全局变量
    window.formMessages = messages[lang];
}

// 修改原有的表单验证函数
function validateForm(name, email, message) {
    const messages = window.formMessages || {
        nameError: '请输入有效的姓名（至少2个字符）',
        emailError: '请输入有效的邮箱地址',
        messageError: '请输入消息（至少10个字符）'
    };
    
    // 验证姓名
    if (!name || name.trim().length < 2) {
        showNotification(messages.nameError, 'error');
        return false;
    }
    
    // 验证邮箱
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!email || !emailRegex.test(email)) {
        showNotification(messages.emailError, 'error');
        return false;
    }
    
    // 验证消息
    if (!message || message.trim().length < 10) {
        showNotification(messages.messageError, 'error');
        return false;
    }
    
    return true;
}

// 修改原有的模拟表单提交函数
function simulateFormSubmission(name, email, message) {
    const submitButton = document.querySelector('.submit-button');
    const messages = window.formMessages || {
        sending: '发送中...',
        sendSuccess: '感谢您的消息，{name}！我会尽快回复您。'
    };
    
    const originalText = submitButton.textContent;
    
    // 显示加载状态
    submitButton.textContent = messages.sending;
    submitButton.disabled = true;
    
    // 模拟网络请求延迟
    setTimeout(() => {
        // 重置表单
        document.getElementById('contactForm').reset();
        
        // 恢复按钮状态
        submitButton.textContent = originalText;
        submitButton.disabled = false;
        
        // 显示成功消息
        const successMessage = messages.sendSuccess.replace('{name}', name);
        showNotification(successMessage, 'success');
        
        console.log('表单提交成功:', { name, email, message });
    }, 2000);
}